package com.wangwq.myspringredis.controller;


import com.wangwq.myspringredis.entity.School;
import com.wangwq.myspringredis.test.TestData;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import  org.springframework.web.bind.annotation.RestController;
import  com.wangwq.myspringredis.util.RedisUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping(value = "/myredis/test")
public class TestController {

        Logger logger = Logger.getLogger(TestController.class);

       @Resource
         RedisUtil redisUtil ;

       @Autowired
       TestData testData;


        @RequestMapping("data")
        public String TestRedis(HttpServletRequest request){
            String name = request.getParameter("key");
            if(StringUtils.isEmpty(name)){
                return "key不能为空!";
            }
            String data = "";
            try{
                data =  redisUtil.get(name).toString();
            }catch (Exception e){
                logger.error(e.getMessage());
                return "该key在redis中没有匹配的值!";
            }
            return "key:"+name+",value:"+data;
        }

    @RequestMapping("hello")
    public String HelloRedis(HttpServletRequest request){
        String key = request.getParameter("key");
        String data = request.getParameter("data");
        if(StringUtils.isEmpty(key)){
            key = "test";
        }
        if(StringUtils.isEmpty(data)){
            data = "123";
        }
       if(redisUtil.set(key,data)){
           return "Redis Set成功!";
       }else{
           return "Redis Set失败!";
       }

    }

   @RequestMapping("/testdata")
    public Object testCachePut(){
       School school = testData.createSchool(TestData.STUDENT);
       return school;
    }


    @RequestMapping("/getdata")
    public Object testCacheGet(HttpServletRequest request){

            String idStr = request.getParameter("id");
            if(!StringUtils.isEmpty(idStr)){
                School school = testData.getSchool(Long.valueOf(idStr));
                if(school == null){
                    return "该id没有对应的值!";
                }
                return school;
            }else{
                return "必须有id参数";
            }


    }

    @RequestMapping("/deldata")
    public Object testCacheEvict(HttpServletRequest request){
        String idStr = request.getParameter("id");
        if(!StringUtils.isEmpty(idStr)){
            testData.delSchool(Long.valueOf(idStr));
           return  "删除成功!";
        }else{
            return "必须有id参数";
        }
    }
}
